package com.sl.pmpclient.activities;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sl.pmpclient.R;
import com.sl.pmpclient.businesses.AuthBusiness;

/**
 * 登录用activity界面
 * 
 * @author 烁灵
 * 
 */
public class LoginActivity extends Activity implements OnClickListener,
		OnKeyListener {
	private EditText usernameText;
	private EditText passwordText;
	private CheckBox remembermeCheck;
	private Button forgetpswBtn;
	private Button loginBtn;
	private Button registerBtn;

	private Handler handler;
	private Thread thread;

	/**
	 * 取出用户被记住的密码
	 * 
	 * @param username
	 * @return
	 */
	private String getRememberedPsw(String username) {
		return AuthBusiness.isUserRemembered(this, username);
	}

	/**
	 * 初始化控件内容
	 */
	private void init_contents() {
		ContentValues remembered_users = AuthBusiness
				.getFirstRememberedUserInfo(this);
		if (remembered_users != null) {
			this.usernameText.setText(remembered_users
					.getAsString("remembered_user_name"));
			this.passwordText.setText(remembered_users
					.getAsString("remembered_user_psw"));
			this.remembermeCheck.setChecked(true);
		}
	}

	/**
	 * 初始化界面
	 */
	private void init_guis() {
		// 取得控件
		this.usernameText = (EditText) this.findViewById(R.id.username_text);
		this.passwordText = (EditText) this.findViewById(R.id.password_text);
		this.remembermeCheck = (CheckBox) this
				.findViewById(R.id.rememberme_check);
		this.forgetpswBtn = (Button) this.findViewById(R.id.forgetpsw_btn);
		this.loginBtn = (Button) this.findViewById(R.id.login_btn);
		this.registerBtn = (Button) this.findViewById(R.id.register_btn);
		// 根据记住的密码读取账户
		init_contents();
		// 绑定监听器
		this.usernameText.setOnKeyListener(this);
		this.loginBtn.setOnClickListener(this);
		this.registerBtn.setOnClickListener(this);
	}

	/**
	 * 初始化handler
	 */
	private void init_handler() {
		this.handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.arg1 != -1) {
					int userid = msg.arg1;
					String username = LoginActivity.this.usernameText.getText()
							.toString();
					String password = LoginActivity.this.passwordText.getText()
							.toString();
					// 若选择记住密码，且本用户未被记住，则记下用户信息
					if (!LoginActivity.this.isRemembered(username)
							&& LoginActivity.this.remembermeCheck.isChecked()) {
						AuthBusiness.rememberUser(LoginActivity.this, username,
								password);
					}
					// 未选中记住密码，则尝试删除记住过的密码
					if (!LoginActivity.this.remembermeCheck.isChecked()) {
						AuthBusiness.deleteRememberedUser(LoginActivity.this,
								username);
					}
					// 记录全局数据
					AuthBusiness.appSetUser(LoginActivity.this, userid,
							username);
					// 切换activity
					Toast.makeText(LoginActivity.this, "登陆成功",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this, HomeActivity.class);
					LoginActivity.this.startActivity(intent);
					finish();
				} else {
					// 错误提示
					Toast.makeText(LoginActivity.this, R.string.loginfail_info,
							Toast.LENGTH_SHORT).show();
				}
			}

		};
	}

	/**
	 * 判断该用户是否被记住了密码
	 * 
	 * @param username
	 * @return
	 */
	private boolean isRemembered(String username) {
		return AuthBusiness.isUserRemembered(this, username) != null;
	}

	/**
	 * 判断该用户是否使用被记住了密码
	 * 
	 * @param username
	 * @return
	 */
	private boolean isRememberedPsw(String username, String password) {
		if (AuthBusiness.isUserRemembered(this, username) != null) { // 如果在数据库中被记住
			if (this.getRememberedPsw(username).equals(password)) { // 并且是使用的记住的密码
				return true;
			}
		}
		// 虽然记住了但重新输入了密码
		return false;
	}

	/**
	 * 登录
	 */
	private void login() {
		// 联网验证

		TextView tv = new TextView(this);
		tv.setText(this.getString(R.string.logining_info));
		this.thread = new Thread() {

			@Override
			public void run() {

				// TODO Auto-generated method stub
				String username = LoginActivity.this.usernameText.getText()
						.toString();
				String password = LoginActivity.this.passwordText.getText()
						.toString();
				int userid = AuthBusiness.loginUser(LoginActivity.this,
						username, password,
						LoginActivity.this.isRememberedPsw(username, password));
				Message msg = new Message();
				msg.arg1 = userid;
				LoginActivity.this.handler.sendMessage(msg);

			}

		};
		this.thread.start();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.equals(this.loginBtn)) {
			login();
		} else if (v.equals(this.registerBtn)) {
			finish();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		this.init_handler();
		this.init_guis();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (v.equals(this.usernameText)) { // 输入用户名时读取记住的密码
			String username = this.usernameText.getText().toString();
			String userpsw = this.getRememberedPsw(username);
			if (userpsw != null) {
				this.passwordText.setText(this.getRememberedPsw(username));
			}
		}
		return false;
	}

}
